import { useCallback, useEffect, useState, useRef } from "react";
import BookingHead from "@/components/booking/BookingHead";
import type { ColumnsType } from "antd/es/table";
import { Divider, Table, Modal, message } from "antd";
import { FileSearchOutlined, ClearOutlined } from "@ant-design/icons";
import { Link, Outlet, useLocation } from "react-router-dom";

import { useDispatch, useSelector } from "react-redux";
import { requestBySelected } from "@/store/modules/reservation";
import type { StoreState, StoreDispatch } from "@/store";

import { requestDeleteoneApi, requestDeletemanyApi } from "@/api/booking";

import moment from "moment";

enum Status {
  All = "全部",
  Wait = "待就诊",
  Past = "已就诊",
  Cancel = "已取消",
}

// 预约挂号
export default function BookRegister() {
  // 列数据
  const [columns, setColumns] = useState<ColumnsType<DataType>>(() => {
    return [
      {
        title: "患者姓名",
        dataIndex: "name",
        align: "center",
      },
      {
        title: "就诊卡号",
        dataIndex: "bookingID",
        align: "center",
      },
      {
        title: "身份证",
        dataIndex: "IDcard",
        align: "center",
      },
      {
        title: "手机号码",
        dataIndex: "tel",
        align: "center",
      },
      {
        title: "挂号科室",
        dataIndex: "department",
        align: "center",
      },
      {
        title: "挂号类型",
        dataIndex: "bookingType",
        align: "center",
      },
      {
        title: "挂号费",
        dataIndex: "cost",
        align: "center",
      },
      {
        title: "挂号状态",
        dataIndex: "status",
        align: "center",
        render: (value) => {
          let wcolor = "#000";
          if (value === "待就诊") {
            wcolor = "#006eff";
          } else if (value === "已就诊") {
            wcolor = "#4dda8b";
          } else {
            wcolor = "#d4380d";
          }
          return <span style={{ color: ` ${wcolor}` }}>{value}</span>;
        },
      },
      {
        title: "就诊日期",
        dataIndex: "bookingDate",
        align: "center",
      },
      {
        title: "候诊时间",
        dataIndex: "waitingTime",
        align: "center",
      },
      {
        title: "预约时间",
        dataIndex: "bookingTime",
        align: "center",
      },
      {
        title: "操作",
        dataIndex: "bookingTime",
        align: "center",
        render: (_, record) => {

          return (
            <>
              {" "}
              <Link
                to={"/Bookingmsg/BookRegister/reservation-detail"}
                state={{ record }}
              >
                <FileSearchOutlined
                  style={{
                    fontSize: "20px",
                    color: "#006eff",
                    padding: "10px",
                  }}
                />
              </Link>
              <ClearOutlined
                style={{ fontSize: "20px", color: "#006eff", padding: "10px" }}
                onClick={() => {
                  rowDeleteRef.current = record._id;
                  //判断勾选的信息与点击的删除图标
                  if (rowSelectionRef.current == rowDeleteRef.current) {
                    console.log("对上了");
                    setDeleteOne(true);
                  } else {
                    console.log("对不上");

                    rowSelectionRef.current === undefined
                      ? // 没勾选，展示删除消息提示
                        success("请勾选需要删除的数据", "error")
                      : rowSelectionRef.current.length === 0
                      ? // 没勾选，展示删除消息提示
                        success("请勾选需要删除的数据", "error")
                      : rowSelectionRef.current.length === 1
                      ? // 勾选的数据与点击删除的数据不一致
                        success("请勾选对应的数据", "error")
                      : // 选中多条信息，展示消息提醒
                        success(
                          "只能一条删除数据，批量删除请点击 [批量删除] 按钮",
                          "error"
                        );
                  }
                }}
              />
            </>
          );
        },
      },
    ];
  });

  // 路由信息
  const { pathname } = useLocation();

  // 从仓库获取预约表格数据
  const dataSource = useSelector(
    (state: StoreState) => state.reservation.dataSource
  );

  // 单选框
  const [radioValue, setRadioValue] = useState(Status.All);
  // 时间
  const [time1, setTime1] = useState<number>(0);
  const [time2, setTime2] = useState<number>(0);
  // 层级
  const [department, setDepartment] = useState();
  // 输入框
  const [input, setInput] = useState("");

  // 对话框（删除一条）
  const [deleteOne, setDeleteOne] = useState(false);
  // 对话框（删除多条）
  const [deleteMany, setDeleteMany] = useState(false);

  // 删除提示
  const [messageApi, contextHolder] = message.useMessage();

  // 选中信息
  const rowSelectionRef = useRef<React.Key[]>();
  // 点击删除图标获取对应ID
  const rowDeleteRef = useRef<React.Key[]>();

  const dispatch: StoreDispatch = useDispatch();

  // 请求预约表格全部数据
  const getTabData = useCallback(async () => {
    // console.log("请求全部数据的方法");
    await dispatch(
      requestBySelected({
        status: radioValue,
        time1: time1,
        time2: time2,
        department: department,
        input: input,
      })
    );
  }, [dispatch, radioValue, time1, time2, department, input]);

  useEffect(() => {
    getTabData();
  }, [getTabData]);

  // 处理单选框选择
  const handelRadioAction = useCallback(
    async (value: Status) => {
      if (radioValue !== value) {
        // console.log("单选框请求");

        setRadioValue(value);

        // 根据单选框选中的值筛选数据
        await dispatch(
          requestBySelected({
            status: value,
            time1: time1,
            time2: time2,
            department: department,
            input: input,
          })
        );
      }
    },
    [dispatch, time1, time2, department, input, radioValue]
  );

  // 处理时间
  const getMidnightTimestamp = useCallback((timestamp: any) => {
    const date = moment(timestamp).startOf("day");
    return date.valueOf();
  }, []);

  // 处理日期选择器选择的值
  const handelTimeAction = useCallback(
    async (value: any) => {
      let timemin;
      let timemax;

      if (value[0] === 0 && value[1] === 0) {
        // 重置后时间为 0
        timemin = value[0];
        timemax = value[1];
      } else {
        // console.log("时间请求");
        // 处理时间成凌晨的
        timemin = getMidnightTimestamp(value[0]);
        timemax = getMidnightTimestamp(value[1]);
      }
      setTime1(timemin);
      setTime2(timemax);

      // 请求时间区间内的数据
      await dispatch(
        requestBySelected({
          status: radioValue,
          time1: timemin,
          time2: timemax,
          department: department,
          input: input,
        })
      );
    },
    [getMidnightTimestamp, dispatch, radioValue, department, input]
  );

  // 选择科室
  const handelDepartmentAction = useCallback(
    async (value: any) => {
      if (department !== value) {
        // console.log("科室请求");

        // 设置，保存层级值
        setDepartment(value);
        // 请求数据
        await dispatch(
          requestBySelected({
            status: radioValue,
            time1: time1,
            time2: time2,
            department: value,
            input: input,
          })
        );
      }
    },
    [dispatch, radioValue, time1, time2, input, department]
  );

  // 输入框
  const handelInputAction = useCallback(
    async (value: any) => {
      if (input !== value) {
        // console.log("输入框请求");

        setInput(value);
        // 请求数据
        await dispatch(
          requestBySelected({
            status: radioValue,
            time1: time1,
            time2: time2,
            department: department,
            input: value,
          })
        );
      }
    },
    [dispatch, radioValue, time1, time2, department, input]
  );

  // 重置
  const handelResetAction = useCallback(
    (isReset: boolean) => {
      if (isReset) {
        // console.log("重置");

        setRadioValue(Status.All);
        setTime1(0);
        setTime2(0);
        setDepartment(undefined);
        setInput("");

        getTabData();
      }
    },
    [getTabData]
  );

  // 多选框选择
  const onChange = useCallback(
    (selectedRowKeys: React.Key[]) => {
      rowSelectionRef.current = selectedRowKeys;
      console.log("多选框勾选：", rowSelectionRef.current);
    },
    [rowSelectionRef]
  );

  // 点击删除的删除提示
  const success = useCallback(
    (text: string, type: any) => {
      messageApi.open({
        type: type,
        content: text,
        className: "custom-class",
        duration: 2,
        style: {
          marginTop: "50vh",
          marginLeft: "30vh",
        },
      });
    },
    [messageApi]
  );

  // 取消按钮事件
  const handleCancel = useCallback(() => {
    // 关闭对话框
    setDeleteOne(false);
    setDeleteMany(false);
  }, []);

  // 确定删除事件(删除一条)
  const deleteOneAction = useCallback(async () => {
    // 关闭对话框
    setDeleteOne(false);

    // 连接删除接口删除数据
    const {
      data: { status },
    } = await requestDeleteoneApi({ id: rowDeleteRef.current });

    if (status === 200) {
      success("数据已成功删除", "success");
      rowSelectionRef.current = undefined;
      getTabData();
    } else {
      success("数据删除失败", "error");
    }
  }, [success, getTabData]);

  // 点击批量删除
  const OpenDeleteManyAction = useCallback(() => {
    console.log("点击批量删除", rowSelectionRef.current);

    rowSelectionRef.current === undefined
      ? // 没勾选数据
        success("请勾选需要批量删除的数据", "error")
      : rowSelectionRef.current.length === 0
      ? // 没勾选数据
        success("请勾选需要批量删除的数据", "error")
      : rowSelectionRef.current.length === 1
      ? // 只勾选了一条数据
        success("批量删除需要勾选多条数据", "error")
      : // 勾选多条数据，打开删除对话框
        setDeleteMany(true);
  }, [success]);

  // 批量删除
  const deleteManyAction = useCallback(async () => {
    // 关闭对话框
    setDeleteMany(false);

    const {
      data: { status },
    } = await requestDeletemanyApi({ id: rowSelectionRef.current });

    if (status === 200) {
      success("批量删除", "success");
      rowSelectionRef.current = undefined;
      getTabData();
    } else {
      success("批量删除失败", "error");
    }
  }, [success, getTabData]);

  return (
    <div className="page">
      {/* 预约信息表 */}
      {pathname === "/Bookingmsg/BookRegister" && (
        <div className="page">
          <BookingHead
            onRadio={handelRadioAction}
            onTime={handelTimeAction}
            onDepartment={handelDepartmentAction}
            onInput={handelInputAction}
            isReset={handelResetAction}
            onDelete={OpenDeleteManyAction}
          />
          <div>
            <Divider />
            {dataSource.length === 0 ? (
              <div
                style={{
                  width: "100%",
                  color: "#aaaaaac8",
                  textAlign: "center",
                  fontSize: "20px",
                }}
              >
                暂无数据......
              </div>
            ) : (
              <Table
                rowSelection={{
                  ...{ onChange: onChange },
                }}
                  columns={columns}
                  // dataSource
                dataSource={dataSource}
              />
            )}
            {/* 对话框 */}
            <Modal
              title="删除数据"
              open={deleteOne}
              onOk={deleteOneAction}
              onCancel={handleCancel}
              okText="确认"
              cancelText="取消"
              centered={true}
            >
              <p>确定要删除该数据吗？</p>
            </Modal>
            <Modal
              title="批量删除数据"
              open={deleteMany}
              onOk={deleteManyAction}
              onCancel={handleCancel}
              okText="确认"
              cancelText="取消"
              centered={true}
            >
              <p>确定要批量删除这些数据吗？</p>
            </Modal>
            {contextHolder}
          </div>
        </div>
      )}
      {/* 详情页 */}
      {pathname === "/Bookingmsg/BookRegister/reservation-detail" && <Outlet />}
    </div>
  );
}
